import request from '@/request/index.js';
import config from "@/config/index.js";

export function upload(path, progressFn) {
	let userinfo = uni.getStorageSync('system-userinfo');
	return new Promise((resolve, reject) => {
		var uploadTask = uni.uploadFile({
			url: config.baseURL + '/app-api/infra/file/upload',
			filePath: path,
			name: 'file',
      fileType: 'image',
			header: {
				"tenant-id": uni.getStorageSync("tenantId"),
				// "hospital-id": uni.getStorageSync("hospitalId"),
				"Authorization": "Bearer " + userinfo.accessToken
			},
			success: (res) => {
				if(res.statusCode === 200){
					let data = JSON.parse(res.data);
					if(data.code === 0){
						resolve(data.data);
					}else{
						reject(data.msg);
					}
				}else{
					reject(res.errMsg);
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
		uploadTask.onProgressUpdate((res) => {
			progressFn(res.progress);
		});
	})
	
}

export function batchUpload(tempFilePaths) {
	
	function executeUpload(filePath){
		return new Promise((resolve) => {
			var uploadTask = uni.uploadFile({
				url: config.baseURL + '/app-api/infra/file/upload',
				filePath: filePath,
				name: "file",
				header: {
					"hospital-id": uni.getStorageSync("hospitalId")
				},
				success: (result) => {
					uni.hideLoading();
					if (result.statusCode === 200 && result.data) {
						let res = JSON.parse(result.data);
						if (res.code === 0) {
							resolve(res.data);
						} else {
							console.error(res.msg);
						}
					} else {
						console.error(result.statusCode);
					}
				},
				fail: (err) => {
					console.error(err);
					uni.hideLoading();
				}
			});
			uploadTask.onProgressUpdate((res) => {
				console.log(res);
			});
		});
	}
	
	let executeArr = [];
	for (let i = 0; i < tempFilePaths.length; i++) {
		executeArr.push(executeUpload(tempFilePaths[i]));
	}
	
	return new Promise((resolve) => {
		uni.showLoading({
			title: "上传中",
			mask: true
		});
		Promise.all(executeArr).then((result) =>{
			resolve(result);
			uni.hideLoading();
		}).catch((err) => {
			console.log(err);
			uni.hideLoading();
		});
	});
	
}